package com.azure.bigstore.service;

import com.azure.bigstore.entity.Product;
import com.azure.bigstore.fileUpload.UploadService;
import com.azure.bigstore.repository.ProductRepository;
import org.hibernate.jpa.internal.EntityManagerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * Created by liuhuaibin on 2018/1/23.
 */
@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UploadService uploadService;

    public List<Product> searchProducts(String category, String title){
        return productRepository.findByCategoryAndTitleContaining(category,title);
    }
    public List<Product> searchProductsByKeyword(String title){
        return productRepository.findByTitleContaining(title);
    }
    public List<Product> searchProductsByCategory(String category){
        return productRepository.findByCategory(category);
    }
    public List<Product> searchProductsByCategoryLimit8(String category){
        /*EntityManager entityManager = Persistence.createEntityManagerFactory("myJPA").createEntityManager();
        Query query =  entityManager.createQuery("select p from Product p where category =:category order by num desc");
        query.setParameter("category",category);
        return query.setMaxResults(8).getResultList();*/

        return productRepository.findByCategorylimit8(category);
    }

    public List<Product> getProducts(){
        return productRepository.findAll();
    }
    public List<Product> getProductsOrderByCategory(){
        return productRepository.findAllOrderByCategory();
    }

    public Product getProduct(String id){
        return productRepository.findOne(Long.valueOf(id));
    }

    public Product saveProduct(Product product){
        return productRepository.save(product);
    }
    public Product saveProduct(Product product, MultipartFile file, HttpServletRequest request){

        if(file != null){
            String imgURL = "";
            try {
                imgURL = uploadService.upload(file,request);
            } catch (IOException e) {
                e.printStackTrace();
            }
            product.setCover(imgURL);
        }

        System.out.println("saveProduct:"+product);
        return productRepository.save(product);
    }

    public void deleteProduct(String id){
        productRepository.delete(Long.valueOf(id));
    }

    public List<Product> getHotProducts(List<Long> ids){
        return productRepository.findHotProducts(ids);
    }
}
